<template>
	<view class="store-map-container">
		<!-- 高德地图容器 -->
		<view class="amap-container" id="amap-container">
			<!-- #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ -->
			<map 
				id="map"
				class="map" 
				:latitude="storeLocation.latitude" 
				:longitude="storeLocation.longitude" 
				:markers="[{
					id: 1,
					latitude: storeLocation.latitude,
					longitude: storeLocation.longitude,
					iconPath: '/static/location-pin.png',
					width: 30,
					height: 30
				}]" 
				scale="16" 
				show-location
			></map>
			<!-- #endif -->
		</view>
		
		<!-- 底部门店信息卡片 -->
		<view class="store-info-card">
			<view class="store-title">
				<text>{{storeInfo.name}}</text>
			</view>
			<view class="store-address">
				<text>{{storeInfo.address}}</text>
			</view>
			<view class="store-distance">
				<text>距你 {{storeInfo.distance}}公里</text>
				<text class="estimate-time" v-if="storeInfo.driveTime">🚗 {{storeInfo.driveTime}}</text>
			</view>
			
			<!-- 添加起点信息显示 -->
			<view class="route-info" v-if="false">
				<view class="route-item">
					<text class="label">起点：</text>
					<text class="value">{{ userLocation.latitude === 24.63889 ? '北站家庭附近' : '当前位置' }}</text>
				</view>
				<view class="route-item">
					<text class="label">终点：</text>
					<text class="value">{{storeInfo.name}}</text>
				</view>
			</view>
			
			<!-- 门店营业信息 -->
			<view class="store-business-info" v-if="storeInfo.businessHours">
				<view class="business-item">
					<text class="label">营业时间：</text>
					<text class="value">{{storeInfo.businessHours}}</text>
				</view>
				<view class="business-item" v-if="storeInfo.phone">
					<text class="label">联系电话：</text>
					<text class="value clickable" @click="callStore">{{storeInfo.phone}}</text>
				</view>
				<view class="business-item" v-if="storeInfo.services && storeInfo.services.length">
					<text class="label">提供服务：</text>
					<view class="service-tags">
						<text class="service-tag" v-for="(service, index) in storeInfo.services" :key="index">{{service}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 返回按钮 -->
		<view class="back-btn" @click="goBack">
			<text>←</text>
		</view>

		<!-- 加载中提示 -->
		<view class="loading-container" v-if="loading">
			<view class="loading-box">
				<text class="loading-text">加载中...</text>
			</view>
		</view>

		<!-- 路线规划面板 -->
		<view class="route-panel" v-if="routeStatus.planning">
			<view class="route-panel-content">
				<text>正在为您规划路线...</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			storeId: null,
			storeInfo: {
				name: '',
				address: '',
				distance: '0',
				driveTime: '',
				businessHours: '',
				phone: '',
				services: []
			},
			storeLocation: {
				latitude: 31.343682,
				longitude: 120.638731
			},
			map: null,
			marker: null,
			loading: true,
			isFavorite: false,
			userLocation: {
				latitude: 24.63889, // 厦门北站家庭附近位置
				longitude: 118.06889 // 厦门北站家庭附近位置
			},
			// 添加路线规划状态
			routeStatus: {
				planning: false,
				planned: false
			},
			routePath: null, // 存储路线
			routePanel: null // 路线信息面板
		};
	},
	onLoad(options) {
		if (options.id) {
			this.storeId = options.id;
			this.loadStoreInfo(options.id);
		} else {
			this.loading = false;
			uni.showToast({
				title: '门店ID不存在',
				icon: 'none'
			});
		}
		
		// 获取用户当前位置
		this.getUserLocation();
		
		// 检查是否已收藏
		this.checkIsFavorite();
	},
	onReady() {
		// 页面DOM渲染完成后初始化地图
		this.initMap();
		
		// 页面加载完成后自动进行路线规划
		setTimeout(() => {
			this.routePlan();
		}, 1000);
	},
	methods: {
		// 获取用户当前位置
		getUserLocation() {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					this.userLocation.latitude = res.latitude;
					this.userLocation.longitude = res.longitude;
					
					// 计算与门店的距离
					if (this.storeLocation.latitude && this.storeLocation.longitude) {
						this.calculateDistance();
					}
				},
				fail: (err) => {
					console.error('获取位置失败', err);
				}
			});
		},
		
		// 计算与门店的距离
		calculateDistance() {
			// 这里可以使用高德地图API计算实际驾车距离和时间
			// 简单实现，使用直线距离
			const lat1 = this.userLocation.latitude;
			const lng1 = this.userLocation.longitude;
			const lat2 = this.storeLocation.latitude;
			const lng2 = this.storeLocation.longitude;
			
			if (lat1 && lng1 && lat2 && lng2) {
				const distance = this.getDistance(lat1, lng1, lat2, lng2);
				this.storeInfo.distance = (distance / 1000).toFixed(1);
				
				// 估算驾车时间，假设平均速度为40km/h
				const driveTimeMinutes = Math.round((distance / 1000) / 40 * 60);
				if (driveTimeMinutes < 60) {
					this.storeInfo.driveTime = `约${driveTimeMinutes}分钟`;
				} else {
					const hours = Math.floor(driveTimeMinutes / 60);
					const minutes = driveTimeMinutes % 60;
					this.storeInfo.driveTime = `约${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`;
				}
			}
		},
		
		// 计算两点之间的距离（米）
		getDistance(lat1, lng1, lat2, lng2) {
			const EARTH_RADIUS = 6378137.0;
			const radLat1 = this.rad(lat1);
			const radLat2 = this.rad(lat2);
			const a = radLat1 - radLat2;
			const b = this.rad(lng1) - this.rad(lng2);
			
			const s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2), 2) + 
				Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b/2), 2)));
			return s * EARTH_RADIUS;
		},
		
		rad(d) {
			return d * Math.PI / 180.0;
		},
		
		// 检查是否已收藏
		checkIsFavorite() {
			const favoriteStores = uni.getStorageSync('favoriteStores') || [];
			this.isFavorite = favoriteStores.includes(Number(this.storeId));
		},
		
		loadStoreInfo(id) {
			this.loading = true;
			
			// 调用API获取门店详情
			this.$api.storeApi.getStoreDetail(id)
				.then(res => {
					if (res.code === 200 && res.data) {
						const storeData = res.data;
						
						// 更新门店信息
						this.storeInfo = {
							name: storeData.name || '未知门店',
							address: storeData.address || '地址未知',
							distance: this.storeInfo.distance,
							driveTime: this.storeInfo.driveTime,
							businessHours: storeData.businessHours || '09:00-21:00',
							phone: storeData.phone || '',
							services: storeData.services || ['宠物洗澡', '宠物美容', '宠物寄养']
						};
						
						// 更新位置信息
						if (storeData.latitude && storeData.longitude) {
							this.storeLocation = {
								latitude: storeData.latitude,
								longitude: storeData.longitude
							};
							
							// 更新地图位置
							if (this.map) {
								this.updateMapLocation();
							}
							
							// 重新计算距离
							if (this.userLocation.latitude && this.userLocation.longitude) {
								this.calculateDistance();
							}
						}
					} else {
						// 使用备用数据
						this.useFallbackData(id);
					}
				})
				.catch(err => {
					console.error('获取门店信息失败', err);
					// 使用备用数据
					this.useFallbackData(id);
				})
				.finally(() => {
					this.loading = false;
				});
		},
		
		// 使用备用数据
		useFallbackData(id) {
			// 备用静态数据
			const stores = [
				{
					id: 1,
					name: '苏州龙湖狮山店（线下门店）',
					address: '塔园路181号龙湖苏州狮山天街L4层 狗道（苏州龙湖狮山天街店）',
					businessHours: '10:00-22:00',
					phone: '0512-88888888',
					services: ['宠物洗澡', '宠物美容', '宠物寄养', '宠物用品'],
					latitude: 31.343682,
					longitude: 120.638731
				},
				{
					id: 2,
					name: '苏州中心店（线下门店）',
					address: '苏州市工业园区苏绣路苏州中心北区B1层',
					businessHours: '10:00-22:00',
					phone: '0512-66666666',
					services: ['宠物洗澡', '宠物美容', '宠物医疗'],
					latitude: 31.323472,
					longitude: 120.722368
				},
				{
					id: 3,
					name: '苏州新区永旺店（线下门店）',
					address: '城际路19号永旺梦乐城(苏州新区店)2F-203...',
					businessHours: '09:30-21:30',
					phone: '0512-77777777',
					services: ['宠物用品', '宠物食品'],
					latitude: 31.300452,
					longitude: 120.543197
				},
				{
					id: 4,
					name: '苏州大悦春风里店（线下门店）',
					address: '元和街道御窑路1999号大悦春风里购物中心L...',
					businessHours: '10:00-21:00',
					phone: '0512-55555555',
					services: ['宠物洗澡', '宠物美容'],
					latitude: 31.369845,
					longitude: 120.589631
				},
				{
					id: 5,
					name: '苏州昆山万象汇店（线下门店）',
					address: '玉山镇前进西路1266号昆山万象汇, 负一层B...',
					businessHours: '10:00-22:00',
					phone: '0512-57575757',
					services: ['宠物洗澡', '宠物美容', '宠物医疗', '宠物用品'],
					latitude: 31.384521,
					longitude: 120.981354
				},
				{
					id: 6,
					name: '苏州昆山金鹰店（线下门店）',
					address: '玉山镇珠江中路199号金鹰国际购物中心(昆...',
					businessHours: '09:00-21:30',
					phone: '0512-50505050',
					services: ['宠物美容', '宠物用品'],
					latitude: 31.381890,
					longitude: 120.952541
				}
			];
			
			const store = stores.find(item => item.id == id) || stores[0];
			
			this.storeInfo = {
				name: store.name,
				address: store.address,
				distance: this.storeInfo.distance || '0',
				driveTime: this.storeInfo.driveTime || '',
				businessHours: store.businessHours,
				phone: store.phone,
				services: store.services
			};
			
			this.storeLocation = {
				latitude: store.latitude,
				longitude: store.longitude
			};
			
			// 如果地图已经初始化，则更新位置
			if (this.map) {
				this.updateMapLocation();
			}
			
			// 重新计算距离
			if (this.userLocation.latitude && this.userLocation.longitude) {
				this.calculateDistance();
			}
		},
		
		initMap() {
			// #ifdef APP-PLUS || H5
			// 先设置安全密钥
			window._AMapSecurityConfig = {
				securityJsCode: '633caf9147a0684d1014072fd9f5d7f8'
			};
			
			// 动态加载高德地图JS API
			const script = document.createElement('script');
			script.type = 'text/javascript';
			script.async = true;
			script.src = 'https://webapi.amap.com/maps?v=2.0&key=7005147a2dba1e54ce7cb99d6b443352&callback=initAMap&plugin=AMap.Driving,AMap.Marker';
			document.head.appendChild(script);
			
			// 全局回调函数，在API加载完成后初始化地图
			window.initAMap = () => {
				this.map = new AMap.Map('amap-container', {
					zoom: 16,
					center: [this.storeLocation.longitude, this.storeLocation.latitude]
				});
				
				// 添加商店标记点
				this.marker = new AMap.Marker({
					position: [this.storeLocation.longitude, this.storeLocation.latitude],
					icon: new AMap.Icon({
						size: new AMap.Size(30, 30),
						image: '/static/location-pin.png',
						imageSize: new AMap.Size(30, 30)
					}),
					offset: new AMap.Pixel(-15, -30),
					title: this.storeInfo.name
				});
				
				this.map.add(this.marker);
				
				// 添加起点标记
				this.startMarker = new AMap.Marker({
					position: [this.userLocation.longitude, this.userLocation.latitude],
					icon: new AMap.Icon({
						size: new AMap.Size(25, 25),
						image: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
						imageSize: new AMap.Size(25, 25)
					}),
					offset: new AMap.Pixel(-12, -12),
					title: '起点'
				});
				
				this.map.add(this.startMarker);
				
				// 添加控件
				this.map.plugin(['AMap.ToolBar'], () => {
					this.map.addControl(new AMap.ToolBar({
						position: 'RB'
					}));
				});
			};
			// #endif
			
			// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
			// 小程序环境下使用地图组件
			setTimeout(() => {
				const mapContext = uni.createMapContext('map');
				if (mapContext) {
					mapContext.moveToLocation({
						longitude: this.storeLocation.longitude,
						latitude: this.storeLocation.latitude
					});
				}
			}, 500);
			// #endif
		},
		updateMapLocation() {
			// #ifdef APP-PLUS || H5
			if (this.map && this.marker) {
				this.map.setCenter([this.storeLocation.longitude, this.storeLocation.latitude]);
				this.marker.setPosition([this.storeLocation.longitude, this.storeLocation.latitude]);
			}
			// #endif
		},
		goBack() {
			uni.navigateBack({
				fail: () => {
					uni.redirectTo({
						url: '/pages/map-list/index'
					});
				}
			});
		},
		routePlan() {
			this.routeStatus.planning = true;
			
			// #ifdef APP-PLUS || H5
			// 使用高德地图路线规划
			if (window.AMap) {
				// 首先清除之前的路线
				if (this.routePath) {
					this.map.remove(this.routePath);
					this.routePath = null;
				}
				
				// 使用高德地图驾车路线规划
				window.AMap.plugin('AMap.Driving', () => {
					const driving = new AMap.Driving({
						map: this.map,
						hideMarkers: false,
						policy: AMap.DrivingPolicy.LEAST_TIME // 最快捷模式
					});
					
					// 规划从北站家庭附近到商店的路线
					driving.search(
						[this.userLocation.longitude, this.userLocation.latitude], // 起点，北站家庭附近
						[this.storeLocation.longitude, this.storeLocation.latitude], // 终点，商店位置
						{waypoints: []}, // 途经点
						(status, result) => {
							if (status === 'complete') {
								this.routeStatus.planned = true;
								this.routePath = result.routes[0].path;
								
								// 调整地图视野以包含所有标记点和路线
								this.map.setFitView();
							} else {
								this.routeStatus.planning = false;
							}
						}
					);
				});
			} else {
				// 如果高德地图API未加载，不进行任何操作
				this.routeStatus.planning = false;
			}
			// #endif
			
			// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
			// 小程序环境下使用系统导航但不显示结果
			setTimeout(() => {
				this.routeStatus.planning = false;
				this.routeStatus.planned = true;
			}, 1000);
			// #endif
		},
		showMore() {
			uni.showActionSheet({
				itemList: ['分享', '复制地址', '举报', '查看评价'],
				success: (res) => {
					const index = res.tapIndex;
					if (index === 0) {
						// 分享
						uni.share({
							provider: 'weixin',
							scene: 'WXSceneSession',
							type: 1,
							summary: `${this.storeInfo.name} - ${this.storeInfo.address}`,
							success: function() {
								console.log('分享成功');
							}
						});
					} else if (index === 1) {
						// 复制地址
						uni.setClipboardData({
							data: this.storeInfo.address,
							success: () => {
								uni.showToast({
									title: '地址已复制',
									icon: 'success'
								});
							}
						});
					} else if (index === 2) {
						// 举报
						uni.showToast({
							title: '举报功能开发中',
							icon: 'none'
						});
					} else if (index === 3) {
						// 查看评价
						uni.showToast({
							title: '评价功能开发中',
							icon: 'none'
						});
					}
				}
			});
		},
		showMoreInfo() {
			// 切换显示更多门店信息
			uni.navigateTo({
				url: `/pages/store/detail?id=${this.storeId}`,
				fail: () => {
					uni.showToast({
						title: '门店详情页面开发中',
						icon: 'none'
					});
				}
			});
		},
		locateMyself() {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					this.userLocation.latitude = res.latitude;
					this.userLocation.longitude = res.longitude;
					
					// #ifdef APP-PLUS || H5
					if (this.map) {
						this.map.setCenter([res.longitude, res.latitude]);
					}
					// #endif
					
					// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
					const mapContext = uni.createMapContext('map');
					if (mapContext) {
						mapContext.moveToLocation();
					}
					// #endif
				},
				fail: (err) => {
					console.error('获取位置失败', err);
					uni.showToast({
						title: '获取位置失败，请检查定位权限',
						icon: 'none'
					});
				}
			});
		},
		// 拨打门店电话
		callStore() {
			if (this.storeInfo.phone) {
				uni.makePhoneCall({
					phoneNumber: this.storeInfo.phone,
					fail: () => {
						uni.showToast({
							title: '拨打电话失败',
							icon: 'none'
						});
					}
				});
			}
		}
	}
}
</script>

<style>
.store-map-container {
	width: 100%;
	height: 100vh;
	position: relative;
}

.amap-container {
	width: 100%;
	height: 100%;
}

.map {
	width: 100%;
	height: 100%;
}

.store-info-card {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #ffffff;
	padding: 30rpx;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	z-index: 100;
	max-height: 70vh;
	overflow-y: auto;
}

.store-title {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.store-address {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.store-distance {
	display: flex;
	align-items: center;
	font-size: 26rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.estimate-time {
	margin-left: 20rpx;
}

.more-btn {
	margin-left: auto;
	color: #007aff;
}

/* 门店营业信息样式 */
.store-business-info {
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.business-item {
	display: flex;
	margin-bottom: 10rpx;
}

.business-item .label {
	color: #666;
	font-size: 26rpx;
	width: 160rpx;
}

.business-item .value {
	color: #333;
	font-size: 26rpx;
	flex: 1;
}

.clickable {
	color: #007aff;
}

.service-tags {
	display: flex;
	flex-wrap: wrap;
}

.service-tag {
	background-color: #e6f7ff;
	color: #1890ff;
	font-size: 24rpx;
	padding: 4rpx 12rpx;
	border-radius: 8rpx;
	margin-right: 10rpx;
	margin-bottom: 10rpx;
}

.action-buttons {
	display: flex;
	justify-content: center;
	border-top: 1px solid #f0f0f0;
	padding-top: 20rpx;
}

.action-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.route-plan-btn {
	background: linear-gradient(to right, #2b85e4, #1989fa);
	color: white;
	border-radius: 30rpx;
	padding: 10rpx 30rpx;
	width: 150rpx;
	box-shadow: 0 4rpx 10rpx rgba(25, 137, 250, 0.25);
	transition: all 0.2s ease;
}

.route-plan-btn:active {
	transform: scale(0.95);
	box-shadow: 0 3rpx 8rpx rgba(25, 137, 250, 0.3);
}

.route-plan-btn .icon {
	color: white;
	font-size: 28rpx;
	margin-bottom: 3rpx;
}

.route-plan-btn text {
	color: white;
	font-size: 22rpx;
	font-weight: 500;
	letter-spacing: 1rpx;
}

.icon {
	font-size: 40rpx;
	margin-bottom: 10rpx;
}

.back-btn {
	position: absolute;
	top: 50rpx;
	left: 30rpx;
	width: 80rpx;
	height: 80rpx;
	background-color: #fff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	font-size: 40rpx;
	z-index: 100;
}

/* 加载中样式 */
.loading-container {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(255, 255, 255, 0.6);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 999;
}

.loading-box {
	background-color: rgba(0, 0, 0, 0.7);
	padding: 20rpx 40rpx;
	border-radius: 10rpx;
}

.loading-text {
	color: #fff;
	font-size: 28rpx;
}

/* 路线规划面板样式 */
.route-panel {
	display: none;
}

/* 添加起点信息显示样式 */
.route-info {
	display: none;
}
</style> 